package net.vinote.smart.platform.service.handler;

import java.sql.SQLException;

import net.vinote.smart.platform.comm.StringFunction;
import net.vinote.smart.platform.module.database.DBManager;
import net.vinote.smart.platform.module.database.DBManagerFactory;
import net.vinote.smart.platform.module.database.DBTransaction;
import net.vinote.smart.platform.module.database.bo.BizObject;
import net.vinote.smart.platform.service.GeneralTools;
import net.vinote.smart.platform.service.dw.handler.CommonHandler;
import net.vinote.smart.platform.service.dw.handler.HandlerPerimissionAnnotation;
import net.vinote.smart.platform.service.util.Permission;
import net.vinote.smart.platform.service.util.Permission.PermissionEnum;

@HandlerPerimissionAnnotation(
		insert = @Permission(PermissionEnum.SMART_USER_INFO_INSERT),
		update = @Permission(PermissionEnum.SMART_USER_INFO_UPDATE),
		delete = @Permission(PermissionEnum.SMART_USER_INFO_DELETE),
		query = @Permission(PermissionEnum.SMART_USER_INFO_QUERY))
public class UserInfoHandler extends CommonHandler {

	@Override
	public void initDisplayForEdit(BizObject bo) {
		setReadOnly("UserID", true);
		if (!StringFunction.isBlank(bo.getAttribute("PassWord"))) {
			decodePassword(bo);
		}
	}

	@Override
	protected void beforeUpdate(BizObject bo, DBTransaction tx) {
		encodePassword(bo);
	}

	@Override
	protected void beforeInsert(BizObject bo, DBTransaction tx) {
		encodePassword(bo);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.zjw.platform.service.dw.handler.CommonHandler#afterInsert(com.zjw
	 * .platform.module.database.bo.BizObject,
	 * com.zjw.platform.module.database.DBTransaction)
	 */
	protected void afterInsert(BizObject bo, DBTransaction tx) {
		decodePassword(bo);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.zjw.platform.service.dw.handler.CommonHandler#afterUpdate(com.zjw
	 * .platform.module.database.bo.BizObject,
	 * com.zjw.platform.module.database.DBTransaction)
	 */
	protected void afterUpdate(BizObject bo, DBTransaction tx) {
		decodePassword(bo);
	}

	private void encodePassword(BizObject bo) {
		bo.setAttribute(
				"PassWord",
				GeneralTools.encrypt(bo.getAttribute("PassWord"),
						GeneralTools.getAesKey(bo.getAttribute("UserID"))));
	}

	private void decodePassword(BizObject bo) {
		bo.setAttribute(
				"PassWord",
				GeneralTools.decrypt(bo.getAttribute("PassWord"),
						GeneralTools.getAesKey(bo.getAttribute("UserID"))));
	}

	@Override
	protected void beforeDelete(BizObject bo, DBTransaction tx)
			throws SQLException {
		DBManager bm = DBManagerFactory.getInstance("user_role_rela");
		tx.join(bm);
		bm.deleteWhereSql("userID=?", bo.getAttribute("UserID"));
	}

}
